package com.cskaoyan.transfer;

import com.cskaoyan.utils.JDBCUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ServiceLoader;

/**
 * 创建日期: 2022/11/17 15:59
 *
 * @author ciggar
 *
 * 事务的使用
 */
public class TransferDemo {

    public static void main(String[] args) throws SQLException {

        Boolean ret = transfer("风华哥", "长风", 2000);

        if (ret) {
            System.out.println("转账成功！！");
        }else {
            System.out.println("转账失败！！");
        }

    }


    // 转账的方法
    /**
     * 创建日期：2022/11/17 16:00
     * @param fromName  转账发起人
     * @param toName    转账受益人
     * @param money     转账金额
     * @return java.lang.Boolean
     * @author ciggar
     */
    public static Boolean transfer(String fromName, String toName,Integer money) throws SQLException {

        Connection connection = JDBCUtils.getConnection();
        PreparedStatement decrStatement = null;
        PreparedStatement addStatement = null;

        // 开启事务
        connection.setAutoCommit(false);

        Boolean flag = false;

        try {

            // 给转账发起人扣钱
            decrStatement = connection.prepareStatement("update account set money = money - ? where name = ? and money >= ?");
            decrStatement.setInt(1, money);
            decrStatement.setString(2, fromName);
            decrStatement.setInt(3, money);
            int affectedRows = decrStatement.executeUpdate();

            if (affectedRows < 1) {
               throw new RuntimeException("扣钱失败！");
            }

            // int i = 1 / 0;

            // 给转账受益人加钱
            addStatement = connection.prepareStatement("update account set money = money + ? where name = ?");
            addStatement.setInt(1, money);
            addStatement.setString(2, toName);
            int affectedRows2 = addStatement.executeUpdate();

            if (affectedRows2 < 1) {
                throw new RuntimeException("加钱失败！");
            }

            // 提交事务
            connection.commit();
            flag = true;

        }catch (Exception ex) {
            ex.printStackTrace();
            // 回滚事务
            connection.rollback();
            flag =false;
        }finally {
            // 关闭资源
            if (addStatement != null) addStatement.close();
            if (decrStatement != null) decrStatement.close();
            connection.close();
        }
        return flag;

    }

}
